

#import "NSString+xhqExtension.h"
#import "SVProgressHUD.h"
#import "GTMBase64.h"


@implementation NSString (xhqExtension)
-(CGFloat)xhq_widthWithFont:(UIFont *)font{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(MAXFLOAT, 100);
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.width;
}

-(CGFloat)xhq_realHeightWithLabel:(UILabel *)label2 maxW:(CGFloat)maxW{
    label2.text = self;
    CGSize labelSize = [label2 sizeThatFits:CGSizeMake(maxW, MAXFLOAT)];
    CGFloat height = ceil(labelSize.height) + 1;
    return height;
}
- (CGSize)xhq_sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size;
}
//
//- (CGSize)sizeWithFont:(UIFont *)font
//{
//    [self sizeWithFont:font constrainedToSize:CGSizeMake(0, 0) lineBreakMode:NSLineBreakByWordWrapping];
//    return [self sizeWithFont:font maxW:MAXFLOAT];
//}


#pragma mark 清空字符串中的空白字符
- (NSString *)trimString
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

#pragma mark 是否空字符串
- (BOOL)xhq_isEmptyString
{
    if (self == nil) {
        return YES;
    }
    return (self.length == 0);
}

#pragma mark 返回沙盒中的文件路径
/**
 *  沙盒全路径
 *
 *  @return 返回沙盒全路径
 */
- (NSString *)documentsPath
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    return [path stringByAppendingPathComponent:self];
}


/**
 *  沙盒全路径
 *
 *  @return 返回沙盒全路径
 */
- (NSString *)temp
{
    NSString *path =NSTemporaryDirectory();
    return [path stringByAppendingPathComponent:self];
}

#pragma mark 写入系统偏好
- (void)saveToNSDefaultsWithKey:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] setObject:self forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


+(NSString *)stringFromNSDefaultsWithKey:(NSString *)key
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:key];
}


- (NSString *)firstCharactor
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:self];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}


- (NSString *) pinyinStr {
    NSMutableString *source = [self mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pinYin = [source capitalizedString];
    return pinYin;
}



//177号码 当做不是手机号
//- (BOOL)telString
//{
//
//
//
//    //1[0-9]{10}
//
//    //^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$
//
//    //    NSString *regex = @"[0-9]{11}";
//
//    NSString *regex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
//
//    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
//
//    BOOL isMatch = [pred evaluateWithObject:self];
//
//    if (!isMatch) {
//
//        //        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入正确的手机号码" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        //
//        //        [alert show];
//
//
//
//
//        return NO;
//
//    }
//    return YES;
//}

-(void)showHUD
{
    
    if (![self length]) {
        return;
    }
    
    MBProgressHUD *hud = nil;
    
    //     NSLog(@"xxx  字符串%@",[[UIApplication sharedApplication].windows lastObject]);
    hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].windows lastObject] animated:YES];
    
    // Configure for text only and offset down
    hud.animationType = MBProgressHUDAnimationZoomOut;
    hud.mode = MBProgressHUDModeText;
    hud.userInteractionEnabled = NO;
    hud.labelText = self ;//
    //              hud.labelText =  @"无法连接到服务器，请检查网络设置";
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:1.8];
    
    
}

-(void)showError{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    [SVProgressHUD setBackgroundColor:HEX_RGBA(0x000000, 0.8)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD setMinimumDismissTimeInterval:1];
     [SVProgressHUD showErrorWithStatus:self];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            
             [SVProgressHUD dismiss];
        });
    });
    
}
-(void)showSuceess{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    [SVProgressHUD setBackgroundColor:HEX_RGBA(0x000000, 0.8)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD setMinimumDismissTimeInterval:1];
    [SVProgressHUD showSuccessWithStatus:self];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
        });
    });
}


-(void)showHUDToView:(UIView *)view
{
    
    if ([self length] == 0) {
        return;
    }
    //    NSLog(@"xxx  字符串%@",[[UIApplication sharedApplication].windows lastObject]);
    MBProgressHUD *hud = nil;
    
    hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    
    // Configure for text only and offset down
    hud.animationType = MBProgressHUDAnimationZoomOut;
    hud.mode = MBProgressHUDModeText;
    hud.userInteractionEnabled = NO;
    hud.labelText = self ;//
    //              hud.labelText =  @"无法连接到服务器，请检查网络设置";
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:2];
    
    
}

-(void)showHUD:(NSInteger)time
{
    if (IsEmpty(self)) {
        return;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo: [[UIApplication sharedApplication].windows lastObject] animated:YES];
    
    //    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].windows lastObject]  animated:YES];
    //            MBProgressHUD *hud = [[MBProgressHUD alloc] initWithWindow:weakself.window];
    
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.labelText = self ;//
    //              hud.labelText =  @"无法连接到服务器，请检查网络设置";
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:time];
    
    
}

#pragma mark -是否包含字符串ios8之前版本使用
- (BOOL)ContainsStringIOS7:(NSString*)other {
    NSRange range = [self rangeOfString:other];
    return range.length != 0;
}



-(BOOL)isOnlyNumber{
    NSError *error = nil;
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]\\d*$" options:NSRegularExpressionCaseInsensitive error:&error];
    NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
    if (result) {
        return YES;
    }else{
        return NO;
    }
}

- (BOOL)isOnlyZhongWenOrZMSZ{
    
    //发送前先检查输入内容
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z0-9\u4e00-\u9fa5]+$" options:NSRegularExpressionCaseInsensitive error:&error];
    NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
    if (result) {
        return YES;
    }else{
        return NO;
    }
}



- (NSString *)pinyinStr2
{
    NSMutableString *pinyin = [self mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    //    NSLog(@"%@", pinyin);
    return [pinyin stringByReplacingOccurrencesOfString:@" " withString:@""].lowercaseString;
}



-(void)showAlert

{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:self message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
//    [self showHUD];
    
}


/**
 *  生成时间戳
 *
 *  @return 时间戳
 */
+ (NSString *)timeSp
{
    
    
    
    NSTimeInterval  time =[[NSDate date] timeIntervalSince1970];
    return [NSString stringWithFormat:@"%ld",(long)time ];
    //    NSDate *datenow = [NSDate date];
    //    NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    //    NSInteger interval = [zone secondsFromGMTForDate:datenow];
    //    NSDate *localeDate = [datenow  dateByAddingTimeInterval: interval];
    //    NSString *timeSp = [NSString stringWithFormat:@"%d", [localeDate timeIntervalSince1970]];
    //    return timeSp;
}



-(NSMutableAttributedString *)lineString{
    NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:
                              
                              
                              [NSNumber numberWithInteger:NSUnderlineStyleSingle],   NSStrikethroughStyleAttributeName, nil];
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self     attributes:attrDict];
    return  attrStr;
}



-(BOOL)zhengze:(NSString *)strZhengze
{
    
    NSError *error = nil;
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:strZhengze options:NSRegularExpressionCaseInsensitive error:&error];
    NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
    if (result) {
        return YES;
    }else{
        return NO;
    }
    
}



// key跟后台协商一个即可，保持一致
static NSString *const PSW_AES_KEY = @"jingkeyunwang201";

// 这里的偏移量也需要跟后台一致，一般跟key一样就行
static NSString *const AES_IV_PARAMETER = @"jingkeyunwang201";

//- (NSString*)aci_encryptWithAES {
//    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
//    NSData *AESData = [self AES128operation:kCCEncrypt
//                                       data:data
//                                        key:PSW_AES_KEY
//                                         iv:AES_IV_PARAMETER];
//    NSString *baseStr_GTM = [self encodeBase64Data:AESData];
//    return baseStr_GTM;
//}

//- (NSString*)aci_decryptWithAES {
//
//    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
//    NSData *baseData_GTM = [self decodeBase64Data:data];
//    NSData *baseData = [[NSData alloc]initWithBase64EncodedString:self options:0];
//
//    NSData *AESData_GTM = [self AES128operation:kCCDecrypt
//                                           data:baseData_GTM
//                                            key:PSW_AES_KEY
//                                             iv:AES_IV_PARAMETER];
//    NSData *AESData = [self AES128operation:kCCDecrypt
//                                       data:baseData
//                                        key:PSW_AES_KEY
//                                         iv:AES_IV_PARAMETER];
//
//    NSString *decStr_GTM = [[NSString alloc] initWithData:AESData_GTM encoding:NSUTF8StringEncoding];
//    NSLog(@"decStr_GTM : %@",decStr_GTM);
//    NSString *decStr = [[NSString alloc] initWithData:AESData encoding:NSUTF8StringEncoding];
//
//    return decStr;
//}

/**
 *  AES加解密算法
 *
 *  @param operation kCCEncrypt（加密）kCCDecrypt（解密）
 *  @param data      待操作Data数据
 *  @param key       key
 *  @param iv        向量
 *
 *
 */
//- (NSData *)AES128operation:(CCOperation)operation data:(NSData *)data key:(NSString *)key iv:(NSString *)iv {
//
//    char keyPtr[kCCKeySizeAES128 + 1];  //kCCKeySizeAES128是加密位数 可以替换成256位的
//    bzero(keyPtr, sizeof(keyPtr));
//    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
//    // IV
//    char ivPtr[kCCBlockSizeAES128 + 1];
//    bzero(ivPtr, sizeof(ivPtr));
//    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
//
//    size_t bufferSize = [data length] + kCCBlockSizeAES128;
//    void *buffer = malloc(bufferSize);
//    size_t numBytesEncrypted = 0;
//
//    // 设置加密参数
//    /**
//     这里设置的参数ios默认为CBC加密方式，如果需要其他加密方式如ECB，在kCCOptionPKCS7Padding这个参数后边加上kCCOptionECBMode，即kCCOptionPKCS7Padding | kCCOptionECBMode，但是记得修改上边的偏移量，因为只有CBC模式有偏移量之说
//
//     */
//    CCCryptorStatus cryptorStatus = CCCrypt(operation, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
//                                            keyPtr, kCCKeySizeAES128,
//                                            ivPtr,
//                                            [data bytes], [data length],
//                                            buffer, bufferSize,
//                                            &numBytesEncrypted);
//
//    if(cryptorStatus == kCCSuccess) {
//        NSLog(@"Success");
//        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
//
//    } else {
//        NSLog(@"Error");
//    }
//
//    free(buffer);
//    return nil;
//}

// 这里附上GTMBase64编码的代码，可以手动写一个分类，也可以直接cocopods下载，pod 'GTMBase64'。
/**< GTMBase64编码 */
- (NSString*)encodeBase64Data:(NSData *)data {
    data = [GTMBase64 encodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

/**< GTMBase64解码 */
- (NSData*)decodeBase64Data:(NSData *)data {
    data = [GTMBase64 decodeData:data];
    return data;
}


-(NSString *)quKongge{
    NSString *str = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return str;
}



-(BOOL)isPhoneNumber{
    NSString *pattern = @"^1+\\d{10}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}
@end
